<?php


namespace App\Service;


use App\Models\SiteIp;

class Ip
{

    /**
     * ip地址
     * https://account.ipplus360.com/
     * 18113069917
     * Liuxu2445842
     */

    public function __construct()
    {
    }


    // 根据ip获取地址
    public function getIpAddress($ip)
    {
        // 首先判断ip是否已经查询了
        $ipDb = new SiteIp();
        $info = $ipDb->isCache(true)->oneFind(['ip' => $ip]);
        if(!empty($info)){
            return $info['city'];
        }

        //$city = $this->getIpplus360IpAddress($ip);
        $city = $this->getBaiduIpAddress($ip);

        return $city;
    }

    // 根据ip获取地址：百度
    // 文档 https://lbsyun.baidu.com/faq/api?title=webapi/ip-api-base
    public function getBaiduIpAddress($ip)
    {
        // SK AK 在百度应用里面的设置里面的
        // 远程获取ip的地址
        // https://api.map.baidu.com/location/ip?ip=111.206.214.37&coor=bd09ll&ak=您的AK
        // https://api.map.baidu.com/location/ip?ip=111.206.214.37&coor=bd09ll&ak=您的AK&sn=您的SK
        $appkey = 'XKWxcX3C5uUgsDQ9Df2MPe5cWaRgCZAo';  // 深蓝汇的key
        $sk     = 'zc9fb1ohyP41e8HHcx3b3n8WI7JjgO7T';  // 深蓝汇的sk
        $url    = "https://api.map.baidu.com/location/ip?ip={$ip}&coor=bd09ll&ak=".$appkey."&sn=".$sk;

        //调用sn计算函数，默认get请求
        // SN 验证 没有通过
        $output = 'json';
        $query = array('ip' => $ip, 'output' => $output, 'ak' => $appkey);
        $uri   = '/location/ip/';
        //$sn    = $this->BaiduSN($appkey, $sk, $uri, $query);

        // 获取ip
        // {"address":"CN|四川省|成都市|None|None|100|100","content":{"address":"四川省成都市","address_detail":{"adcode":"110000","city":"成都市","city_code":131,"district":"","province":"四川省","street":"","street_number":""},"point":{"x":"116.41338370","y":"39.91092455"}},"status":0}
        $url  = "https://api.map.baidu.com/location/ip";
        $post = ['ak' => $appkey, 'ip' => $ip, 'coor' => 'bd09ll',];   //  'sn' => $sn,
        $data = $this->request($url, $post);

        // 保存城市
        $city = $this->saveIp($data, $ip);

        return $city;
    }


    // ipplus360获取ip地址
    // https://api.ipplus360.com
    public function getIpplus360IpAddress($ip)
    {
        // 远程获取ip的地址
        // https://api.ipplus360.com/ip/geo/v1/street/psi/?key=您申请的KEY&ip=您需要查询的ip&coordsys=WGS84&area=multi
        $appkey = 'Dw0LliL6ZmBrEcRuXjlJckrGZGmKiuQCrRqzjUHX0Ls2ujTxIwbifLoiXqRXDSPl';
        $url    = "https://api.ipplus360.com/ip/geo/v1/street/psi/?key={$appkey}&ip={$ip}&coordsys=WGS84&area=multi";
        $url    = "https://api.ipplus360.com/ip/geo/v1/city/";
        $post   = ['key' => $appkey, 'ip' => $ip, 'coordsys' => 'WGS84', 'area' => 'multi',];
        $data   = $this->request($url, $post);

        // 保存城市
        $city = $this->saveIp($data, $ip);

        return $city;
    }

    // 保存地址
    protected function saveIp($data, $ip)
    {
        // 保存数据到数据库
        $city = '';
        $ipDb = new SiteIp();
        if((!empty($data['city'])) && (!empty($data['prov']))){
            $add  = ['city' => $data['city'], 'prov' => $data['prov'], 'ip' => $ip,];
            $res  = $ipDb->insert($add);
            $city = $data['city'];
        }

        return $city;
    }

    // 百度地图 sn 计算
    function BaiduSN($ak, $sk, $url, $querystring_arrays, $method = 'GET')
    {
        if($method === 'POST'){
            ksort($querystring_arrays);
        }
        $querystring = http_build_query($querystring_arrays);

        return md5(urlencode($url.'?'.$querystring.$sk));
    }

    // 执行请求
    protected function request($url, $data)
    {
        try{
            // 初始化curl
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            // 要求结果为字符串且输出到屏幕上
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            // post提交方式
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            // 运行curl
            $data = curl_exec($curl);
            curl_close($curl);

            // 返回ip的地址
            $data = json_decode($data, 1);
            if(isset($data['code']) && ($data['code'] == 'Success')){
                // 保存到数据库
                $data = $data['data'];

                return $data['city'];
            } elseif(isset($data['status']) && ($data['status'] == '0')){
                // 百度
                // 保存到数据库
                $data     = $data['content'];
                $detail   = $data['address_detail'];
                $city     = $detail['city'];
                $province = $detail['province'];
                $code     = $detail['city_code'];

                return ['city' => $city, 'prov' => $province, 'code' => $code,];
            } else{
                return [];
            }
        } catch(\Exception $e){
            echo $e->getMessage();
            echo '<br>';
            echo $e->getLine();

            return [];
        }
    }

}


